#pragma once
#include<pthread.h>
#include<iostream>
#include<queue>
#include"Task.hpp" 
#include"Log.hpp"
#define NUM 6
class ThreadPool
{
private:
    int num;
    pthread_mutex_t lock;
    pthread_cond_t cond;
    std::queue<Task> task_queue;
    static ThreadPool* single_instance; 
    bool stop;
    ThreadPool(int _num=NUM,bool _stop=false):num(_num),stop(_stop)
    {
        pthread_mutex_init(&lock,nullptr);
        pthread_cond_init(&cond,nullptr);
    }
    ThreadPool(const ThreadPool&) {}
public:
    bool TaskQueueIsEmpty()
    {
        return task_queue.empty();
    }
    static ThreadPool* getinstance()
    {
        static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
        if(single_instance==nullptr)
        {
            pthread_mutex_lock(&_mutex);
            if(single_instance==nullptr)
            {
                single_instance=new ThreadPool();
                single_instance->InitThreadPool();
            }
            pthread_mutex_unlock(&_mutex);
        }
        return single_instance;
    }
    static void* ThreadRoutine(void* args)
    {
        ThreadPool* tp=(ThreadPool*)args;
        while(true)
        {
            Task t;
            tp->Lock();
            while(tp->TaskQueueIsEmpty())
            {
                tp->ThreadWait();
            }
            tp->PopTask(t);
            tp->Unlock();
            t.ProcessOn();
        }
    }
    void Lock()
    {
        pthread_mutex_lock(&lock);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&lock);
    }
    void ThreadWait()
    {
        pthread_cond_wait(&cond,&lock);
    }
    void ThreadWakeup()
    {
        pthread_cond_signal(&cond);
    }
    void PushTask(const Task& in)
    {
        Lock();
        task_queue.push(in);
        Unlock();
        ThreadWakeup();
    }
    bool InitThreadPool()
    {
        for(int i=0;i<NUM;i++)
        {
            pthread_t tid;
            if(pthread_create(&tid,nullptr,ThreadRoutine,(void*)this)!=0)
            {
                  LOG(FATAL, "create thread pool error!");
                    return false;
            }
        }
         LOG(INFO, "create thread pool success!");
        return true;
    }
    void PopTask(Task& task)
    {
        task=task_queue.front();
        task_queue.pop();
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&lock);
        pthread_cond_destroy(&cond);
    }
};
ThreadPool* ThreadPool::single_instance=nullptr;